package com.syqc.monitor.ui.stopcar

import android.view.WindowManager
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.syqc.adapter.ChooseTimeAdapter
import com.syqc.base.BaseReportViewModel
import com.syqc.base.BaseSureActivity
import com.syqc.choose.car.ChooseCarActivity
import com.syqc.choose.teamcar.TeamsCarsActivity
import com.syqc.comlib.custom.timer.CustomDatePicker
import com.syqc.comlib.custom.timer.DateFormatUtils
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.comlib.utils.startActivityTo
import com.syqc.monitor.ParamsUtil
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityStopCarBinding
import com.syqc.monitor.databinding.IncludeChooseCarTimeBinding
import com.syqc.monitor.databinding.IncludeChooseFastTimeBinding
import com.syqc.monitor.databinding.IncludeRecyclerWrapBinding
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil
import com.syqc.utils.TimeUtil
import com.syqc.utils.ToolsUtil

/**
 *@Author Jasper
 *@Time   2020/12/11
 *@Desc   停车统计
 */
class StopCarActivity : BaseSureActivity<ActivityStopCarBinding>(ActivityStopCarBinding::inflate) {

    private lateinit var mReportVB: IncludeChooseFastTimeBinding
    private lateinit var mRecyclerVB: IncludeRecyclerWrapBinding
    lateinit var mChooseVB: IncludeChooseCarTimeBinding

    private val mViewModel by viewModels<StopCarViewModel>()


    val mBaseViewModel: BaseReportViewModel
        get() = mViewModel

    val titleId: Int
        get() = R.string.title_report_stop_car

    override fun initView() {
        super.initView()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        mReportVB = IncludeChooseFastTimeBinding.bind(binding.root)
        mRecyclerVB = IncludeRecyclerWrapBinding.bind(binding.root)
        mChooseVB = IncludeChooseCarTimeBinding.bind(binding.root)
        if (titleId != 0) {
            ToolbarHelper.setToolbar(this, titleId)
        }
        mBaseViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)


        mRecyclerVB.recyclerWrap.layoutManager = GridLayoutManager(this, 4)
        mRecyclerVB.recyclerWrap.adapter = mAdapter.apply {
            setNewInstance(mBaseViewModel.timeList)
            setOnItemClickListener { _, _, position ->
                index = position
                notifyDataSetChanged()
                mBaseViewModel.chooseTime(position)
            }
        }

        mBaseViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            mChooseVB.lrvStartTime.setRightText(it)
        }

        mBaseViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            mChooseVB.lrvEndTime.setRightText(it)
        }

        initIntent()
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)
        mViewModel.dataObserver().autoDispose(scopeProvider).subscribe {
            DataUtil.stopCar = it
            startActivityTo<StopCarInfoActivity>(this) {
                putExtra(Keys.INTENT_TITLE, mViewModel.carName)
//                putExtra(Keys.INTENT_DATA, it)
                putExtra(
                    Keys.INTENT_TIME,
                    "${
                        mChooseVB.lrvStartTime.getRightText().substring(0, 10)
                    }  ~  ${mChooseVB.lrvEndTime.getRightText().substring(0, 10)}"
                )
            }
        }

        val carIdExtra = intent.getStringExtra(Keys.INTENT_CAR_ID)
        if (carIdExtra != null) return
        val stopCar = ParamsUtil.getStopCarParams()
        if (stopCar.isNullOrEmpty()) return


        binding.ivSwitchAcc.isSelected = stopCar[0].toBoolean()
        binding.editStopLong.setText(stopCar[1])
    }


    private fun initIntent() {
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        val carName = intent.getStringExtra(Keys.INTENT_PLATE) ?: ""
        if (carId == null) return
        mBaseViewModel.carId = carId
        mBaseViewModel.carName = carName
        mChooseVB.lrvChooseCar.setRightText(carName)
        mChooseVB.lrvChooseCar.isEnabled = false
    }

    override fun setListener() {
        mChooseVB.lrvChooseCar.rightClick {
            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsCarsActivity>(this)
            } else {
                launcher.launchAct<ChooseCarActivity>(this)
            }
        }

        mChooseVB.lrvStartTime.rightClick {
            mBaseViewModel.isStart = true
            mDatePicker.show(mChooseVB.lrvStartTime.getRightText())
        }
        mChooseVB.lrvEndTime.rightClick {
            mBaseViewModel.isStart = false
            mDatePicker.show(mChooseVB.lrvEndTime.getRightText())
        }

        mSureVB.tvSure.filterFast {
            if (ToolsUtil.isFastClick()) return@filterFast
            val startTime = mChooseVB.lrvStartTime.getRightText()
            val endTime = mChooseVB.lrvEndTime.getRightText()
            mBaseViewModel.isParamOk(startTime, endTime)
            if (mViewModel.carId.isNotEmpty())
                ParamsUtil.saveStopCarParams(
                    mViewModel.switchAcc,
                    mViewModel.duration
                )
        }
        binding.editStopLong.doAfterChanged {
            if (!it.isNullOrEmpty()) {
                if (it.toInt() > 600) {
                    binding.editStopLong.setText("600")
                    binding.editStopLong.setSelection(binding.editStopLong.text.length)
                }
            }
            mViewModel.duration = it.toString()
        }
        binding.flSwitchACC.setOnClickListener {
            mViewModel.switchAcc = !mViewModel.switchAcc
            binding.ivSwitchAcc.isSelected = mViewModel.switchAcc
        }
    }

    private val mAdapter: ChooseTimeAdapter by lazy { ChooseTimeAdapter() }

    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            this,
            callback,
            TimeUtil.normalDate,
            mBaseViewModel.nowTimeFormat(),
            !mBaseViewModel.isSimple
        ).apply {
            setCanShowPreciseTime(!mBaseViewModel.isSimple)
        }
    }


    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mAdapter.index = -1
            mAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, !mBaseViewModel.isSimple)

            if (mBaseViewModel.isStart) {
//                if (mBaseViewModel.isOkStart(time, mChooseVB.lrvEndTime.getRightText())) return
                mChooseVB.lrvStartTime.setRightText(time)
            } else {
//                if (mBaseViewModel.isTimeOk(mChooseVB.lrvStartTime.getRightText(), time)) return
                mChooseVB.lrvEndTime.setRightText(time)
            }
            mDatePicker.dismiss()
        }
    }

    private val launcher = registerResultOk { result ->
        result.data?.let {
            val carId = it.getStringExtra(Keys.INTENT_CAR_ID) ?: ""
            val carName = it.getStringExtra(Keys.INTENT_CAR_NAME) ?: ""
//                val videos = it.getStringExtra(Keys.VIDEO)
            mChooseVB.lrvChooseCar.setRightText(carName)
            mBaseViewModel.carName = carName
            mBaseViewModel.carId = carId
        }

    }


}